package com.sxj.shop.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 石小俊
 * @date 2024年03月20日 18:02
 */
//@WebFilter(urlPatterns = "/*",initParams = {
//        @WebInitParam(name = "encoding", value = "utf-8"),
//        @WebInitParam(name = "contentType", value = "text/html;charset=utf-8")
//})
public class CharacterEncodingFilter implements Filter {

    private FilterConfig config;

    @Override
    public void init(FilterConfig config) throws ServletException {
        System.out.println("**************初始化过滤器**************");
        this.config = config;
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("**************过滤器处理中**************");

        // 处理字符集
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String encoding = config.getInitParameter("encoding");
        String contentType = config.getInitParameter("contentType");
        request.setCharacterEncoding(encoding);
        response.setContentType(contentType);

        // 过滤器放行,可以进入到Servlet或者另一个过滤器中
        filterChain.doFilter(servletRequest,servletResponse);
    }

    @Override
    public void destroy() {
        System.out.println("**************销毁过滤器**************");
    }
}
